﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Script that's run on all objects that implement parallax scrolling.
/// </summary>
public class MoveObjectLeft : MonoBehaviour {

	public float Speed = 0.1f;
	public Transform ChainedObjectsParent;
	public float ReAppendOffset = 0f;
	StopAllPhysics physicsScript;
	GameStarted startedScript;

	// Use this for initialization
	void Start () {
		this.physicsScript = (StopAllPhysics)GameObject.Find("Scripts").GetComponent(typeof(StopAllPhysics));
		this.startedScript = (GameStarted)GameObject.Find("Scripts").GetComponent(typeof(GameStarted));
	}
	
	// Update is called once per frame
	void Update () {
	}

	void FixedUpdate() {
		if (!physicsScript.GameOver && startedScript.GameHasStarted)
		{
			Vector3 vec = this.transform.position;
			vec.x -= Speed;
			this.transform.position = vec;
		}
	}

	void OnTriggerEnter2D(Collider2D other) {
		if (other.tag == "Wall") {
			float maxX = -20f;
			for (int z=0;z<ChainedObjectsParent.childCount;z++)		
			{
				Transform tform = ChainedObjectsParent.GetChild(z);
				SpriteRenderer rend = (SpriteRenderer)tform.gameObject.GetComponent(typeof(SpriteRenderer));
				maxX = tform.position.x + rend.bounds.size.x > maxX ? tform.position.x + rend.bounds.size.x : maxX;
			}
			Vector3 vec = this.transform.position;
			vec.x = maxX;
			vec.x += ReAppendOffset;
			this.transform.position = vec;
			if (this.name == "ColumnTop" || this.name == "ColumnBottom") {
				float newValue = UnityEngine.Random.Range(5.9f,9.5f);
				Vector3 vec2 = this.transform.localPosition;
				vec2.y = newValue;
				this.transform.localPosition = vec2;
			}
		}
	}
}
